"""
https://redis.com/glossary/redis-hashes/
https://stackoverflow.com/questions/9112269/iterating-through-keys-in-redis
https://redis.io/commands/exists/
https://redis.io/commands/hexists/
"""

import redis
from PyCmpltrtok.common import get_now_string_short, sep

redisDb = redis.Redis('localhost', 6379, 0)

r = redisDb.hset('map001', 'first_key', '初始值'.encode('utf8'))
print('hset r:', r)

sep('insert x10')
xkeys = []
for i in range(10):
    xkey = f'k{i:03d}'
    redisDb.hset('map001', xkey, f'值{i:03d}'.encode('utf8'))
    xkeys.append(xkey)

sep('get x10')
for i, xkey in enumerate(xkeys):
    print(i, xkey, redisDb.hget('map001', xkey).decode('utf-8'))

sep('remove x3')
for i in range(3, 6):
    xkey = f'k{i:03d}'
    r = redisDb.hdel('map001', xkey)  # hash delete = hdel
    print('r', i, r)

sep('get all')
for i, xkey in enumerate(xkeys):
    xvalue = redisDb.hget('map001', xkey)
    if xvalue is not None:
        xvalue = xvalue.decode('utf-8')
    print(i, xvalue)

sep('hscan')
r = redisDb.hscan('map001', 0)
print(type(r), r)
xdict = r[1]
print(type(xdict), xdict)

sep('all from hscan')
for k, v in xdict.items():
    print(k, v.decode('utf-8'))

sep('hscan with prefix')
r = redisDb.hscan('map001', 0, 'k0*')
xdict = r[1]
for k, v in xdict.items():
    print(k, v.decode('utf-8'))

sep('all over')
